# coding=utf-8
# -*- coding: UTF-8 -*-
#
# This file is part of the kernelstudio package.
#
# (c) 2014-2025 zlin <admin@kernelstudio.com>
#
# For the full copyright and license information, please view the LICENSE file
# that was distributed with this source code.
import typing as t

import yaml

from ksai.document.context import DocumentSection
from ksai.document.extractor.extractor import AbstractDocumentExtractor, DocumentExtractorException
from ksai.persistence.storage.attachment import Attachment


class YamlDocumentExtractor(AbstractDocumentExtractor):

    def __init__(self):
        super().__init__()

    def do_extract(self, attachment: Attachment) -> t.List[DocumentSection]:
        try:
            yaml_data = yaml.safe_load_all(attachment.content_string)
            return [DocumentSection(
                text=t.cast(str, yaml.dump_all(yaml_data, allow_unicode=True, sort_keys=False)),
            )]
        except (UnicodeDecodeError, yaml.YAMLError) as e:
            raise DocumentExtractorException(f"Extract yaml file error: {e}") from e

    def extensions(self) -> t.List[str]:
        return ["yaml", "yml"]

    def mimes(self) -> t.List[str]:
        return ["text/yaml", "text/yml", "application/x-yaml"]
